//
//  SJNetWorkTool.m
//  Recycling
//
//  Created by jzd on 2018/5/22.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "SJNetWorkTool.h"
#import "SJRootChoose.h"

@interface SJNetWorkTool ()
@property (strong,nonatomic)NSString *signature;
@property (strong,nonatomic)NSString *timestamp;
@end

@implementation SJNetWorkTool

-(NSString *)timestamp{
    return [NSString currentTimeStr];
}

static SJNetWorkTool * instance;
+ (instancetype)sharedTool {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL:nil];
        instance.responseSerializer = [AFJSONResponseSerializer serializer];
        instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        instance.requestSerializer.timeoutInterval = 30.0f;
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/html", nil];
        
        
    });
    
    return instance;
}
- (void)requestWithURLString: (NSString *)URLString
                  parameters: (NSDictionary *)parameters
                      method: (HttpMethod)method
                    callBack: (void(^)(id responseObject, NSError *error))callBack {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",SJSeverce,URLString];

    SJLog(@"url ---- %@",url);
    SJLog(@"%@",parameters);
    //判断请求方法是GET还是POST
    if (method == GET) {
        //调用AFN框架的方法
        [self GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            SJLog(@"%@",responseObject);
            //如果请求成功，则回调responseObject
            callBack(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            SJLog(@"%@---%@",task.response,error);
            if (error.code == -1009) {
                [[UIApplication sharedApplication].keyWindow showToast:@"网络不可用" completion:nil];
                callBack(nil,error);
            }else if (error.code == -1001){
                [[UIApplication sharedApplication].keyWindow showToast:@"请求超时" completion:nil];
                callBack(nil,error);
            }else if(error.code == -1011) {
//                BOOL resultD = [SJRootChoose synclogin];
//                if (resultD) {
//                    [self requestWithURLString:URLString parameters:parameters method:method callBack:callBack];
//                }else{
                    callBack(nil,error);
//                }
            }else{
                if (error.code != -999) {
                    [[UIApplication sharedApplication].keyWindow showToast:error.localizedDescription completion:nil];
                    callBack(nil,error);
                }else{
                    callBack(nil,error);
                }
            }
        }];
    }
    
    if (method == POST) {
        [self POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            SJLog(@"%@",responseObject);
            callBack(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            SJLog(@"%@---%@",task.response,error);
            if (error.code == -1009) {
                [[UIApplication sharedApplication].keyWindow showToast:@"网络不可用" completion:nil];
                callBack(nil,error);
            }else if (error.code == -1001){
                [[UIApplication sharedApplication].keyWindow showToast:@"请求超时" completion:nil];
                callBack(nil,error);
            }else if(error.code == -1011) {
//                BOOL resultD = [SJRootChoose synclogin];
//                if (resultD) {
//                    [self requestWithURLString:URLString parameters:parameters method:method callBack:callBack];
//                }else{
                    callBack(nil,error);
//                }
            }else{
                if (error.code != -999) {
                    [[UIApplication sharedApplication].keyWindow showToast:error.localizedDescription completion:nil];
                    callBack(nil,error);
                }else{
                    callBack(nil,error);
                }
            }
        }];
    }
}
-(void)loginWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters callBack:(void (^)(id, NSError *))callBack{
    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",SJSeverce,URLString];
    [self POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SJLog(@"%@",responseObject);
        callBack(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            [[UIApplication sharedApplication].keyWindow showToast:@"网络不可用" completion:nil];
        }else if (error.code == -1001){
            [[UIApplication sharedApplication].keyWindow showToast:@"请求超时" completion:nil];
        }else{
            if (error.code != -999) {
                [[UIApplication sharedApplication].keyWindow showToast:error.localizedDescription completion:nil];
            }
        }
        callBack(nil,error);
    }];
}

/**
 多图上传

 */
-(void)uploadPhoto:(NSArray *)photos WithURLString: (NSString *)URLString
        parameters: (NSDictionary *)parameters
          callBack: (void(^)(id responseObject, NSError *error))callBack{
    NSString *url = [NSString stringWithFormat:@"%@%@",SJSeverce,URLString];
    
    SJLog(@"url ---- %@",url);
    SJLog(@"%@",parameters);
    
    [self POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *uploadImage in photos) {
            NSData *imageData = UIImageJPEGRepresentation(uploadImage, 0.1);
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        callBack(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SJLog(@"%@---%@",task.response,error);
        if (error.code == -1009) {
            [[UIApplication sharedApplication].keyWindow showToast:@"网络不可用" completion:nil];
        }else if (error.code == -1001){
            [[UIApplication sharedApplication].keyWindow showToast:@"请求超时" completion:nil];
        }else{
            if (error.code != -999) {
                [[UIApplication sharedApplication].keyWindow showToast:error.localizedDescription completion:nil];
            }
        }
        callBack(nil,error);
    }];
}
@end
